package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import library.and.xps.com.step.EventBusCommond;
import library.and.xps.com.step.R;
import library.and.xps.com.step.SPConstant;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.ChangeTeam;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.TeamHelper;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.model.CreateTeamParam;
import library.and.xps.com.step.m.model.CreateTeamResponce;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;
import library.and.xps.com.step.view.fragment.CreateTeamInfoFragment;
import library.and.xps.com.step.view.fragment.CreateTeamPassFragment;

public class CreateTeamActivity extends BaseActivity implements com.orhanobut.dialogplus.OnClickListener {
    ImageView iv_back;
    TextView actionbar_tv_right, actionbar_tv_title;
    FragmentManager fragmentManager;
    CreateTeamInfoFragment createTeamInfoFragment;
    CreateTeamPassFragment createTeamPassFragment;
    CreateTeamParam createTeamParam;
    private static final String CREATE_TEAM = "CREATE_TEAM";
    private static final String REQUEST_CHANGETEAM = "REQUEST_CHANGETEAM";
    CreateTeamResponce createTeamResponce = null;

    @Override
    protected int getLayout() {
        return R.layout.activity_create_team;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        createTeamInfoFragment = new CreateTeamInfoFragment();
        createTeamPassFragment = new CreateTeamPassFragment();
        createTeamParam = new CreateTeamParam();
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(R.id.container, createTeamPassFragment, "createTeamPassFragment");
        ft.add(R.id.container, createTeamInfoFragment, "createTeamInfoFragment");
        hideFrags();
        ft.show(createTeamInfoFragment).commit();

        iv_back = r2v(R.id.actionbar_iv_back);
        actionbar_tv_right = r2v(R.id.actionbar_tv_right);
        actionbar_tv_title = r2v(R.id.actionbar_tv_title);
        actionbar_tv_right.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        actionbar_tv_right.setText("完成");
        actionbar_tv_title.setText("创建团队");

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                if (createTeamInfoFragment.isHidden()) {
                    actionbar_tv_right.setVisibility(View.GONE);
                    fragmentManager.beginTransaction().show(createTeamInfoFragment).commit();
                } else
                    finish();
                break;
            case R.id.actionbar_tv_right:
                if (ableCreate())
                    doCreateTeam();
                break;
        }
    }

    //创建团队
    void doCreateTeam() {

        String email = JUtils.getSharedPreference().getString(SPConstant.USER_EMAIL, "");

        String jsonObject = RequestParams.getNewInstance()
                .setTname(createTeamParam.getTname())
                .setEnterprise(createTeamParam.getEnterprise())
                .setAddress(createTeamParam.getAddress())
                .setCreater(createTeamParam.getCreater())
                .setType(createTeamParam.getType())
                .setEmail(email)
                .setScale(createTeamParam.getScale()+"")
                .setDescription(createTeamParam.getDescription())
                .setMark(createTeamParam.getMark())
                .setPassword(createTeamParam.getPassword())
                .getJson().toString();

        OkHttpClientUtils.postJsonStringAsync(getApplicationContext(), URLConstants.TEAM.Createteam, jsonObject, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
                JUtils.Log(CREATE_TEAM, "fail");
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                String json = response.getBody();
                Logger.d(json.toString());
                createTeamResponce = new Gson().fromJson(json, CreateTeamResponce.class);

                if (HttpResponsHelper.SuccessResponce(createTeamResponce))
                    saveData();
            }

            @Override
            public void onStart() {
                showDialog();
            }

        }, CREATE_TEAM);
    }

    void hideFrags() {
        createTeamInfoFragment.hide();
        createTeamPassFragment.hide();
    }

    /**
     * 订阅fragment切换事件
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventMainThread(String str) {
        hideFrags();
        if (EventBusCommond.Create_TeamInfoFragment.equals(str)) {
            fragmentManager.beginTransaction().show(createTeamInfoFragment).commit();
        } else if (EventBusCommond.Create_TeamPassFragment.equals(str)) {
            actionbar_tv_right.setVisibility(View.VISIBLE);
            fragmentManager.beginTransaction().show(createTeamPassFragment).commit();
        }

    }

    //订阅 参数传递事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveCreateParam(CreateTeamParam param) {
        if (!TextUtils.isEmpty(param.getTname())) {
            createTeamParam.setTname(param.getTname());
        }
        if (!TextUtils.isEmpty(param.getAddress())) {
            createTeamParam.setAddress(param.getAddress());
        }
        if (!TextUtils.isEmpty(param.getCreater())) {
            createTeamParam.setCreater(param.getCreater());
        }
        if (!TextUtils.isEmpty(param.getDescription())) {
            createTeamParam.setDescription(param.getDescription());
        }
        if (!TextUtils.isEmpty(param.getEnterprise())) {
            createTeamParam.setEnterprise(param.getEnterprise());
        }
        if (!TextUtils.isEmpty(param.getMark())) {
            createTeamParam.setMark(param.getMark());
        }
        if (!TextUtils.isEmpty(param.getType())) {
            createTeamParam.setType(param.getType());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Fragment f = null;
        if (createTeamInfoFragment.isVisible()) {
            f = getSupportFragmentManager().findFragmentByTag(createTeamInfoFragment.getTag());
        } else if (createTeamPassFragment.isVisible()) {
            f = getSupportFragmentManager().findFragmentByTag(createTeamPassFragment.getTag());
        }
        f.onActivityResult(requestCode, resultCode, data);
    }

    boolean ableCreate() {
        if (!TextUtils.isEmpty(createTeamPassFragment.getPassword())) {
            createTeamParam.setPassword(createTeamPassFragment.getPassword());
            return true;
        } else {
            JUtils.Toast("请输入密码");
            return false;
        }
    }

    void saveData() {
        int teamCount = createTeamResponce.getObj().getNumber();
        if (teamCount >1) {
            showHintDialog("团队创建成功,是否切换到此团队?",this);
        } else {
            changeToCurrentTeam();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(DialogPlus dialog, View view) {
        dialog.dismiss();
        switch (view.getId()) {
            case R.id.footer_confirm_button:
                changeToCurrentTeam();
                break;
            case R.id.footer_close_button:
                finish();
                break;
        }
    }

    //改变团队
    void changeToCurrentTeam() {
        String data = URLConstants.TEAM.ChangeTeam + "?userid=" + getUser().getUserid() + "&teamid=" + createTeamResponce.getObj().getTeamid();
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                ChangeTeam changeTeam = new Gson().fromJson(response.getBody(), ChangeTeam.class);

                if (HttpResponsHelper.SuccessResponce(changeTeam)) {
                    TeamHelper.getIns().insertTeam(getUser(), createTeamResponce);
                    finish();
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, REQUEST_CHANGETEAM);
    }

}
